import wepy from 'wepy'
import Cache from './Cache'
import Config from './Config'
/**
 *
 * 基于微信和大梦想Server的双重用户认证
 */
class Auth {
  constructor () {
    this.cache = new Cache
  }

  async authenticate(reqType) {
    //1. checkSession
    let checkSession = await this.checkSession()
    console.log('checkSession : ', checkSession)
    if(checkSession) {
      //session is ok
      return true
    }
    //2. wx login
    console.log('begin wxLogin')
    let wxLogin = await this.wxLogin()

    if (!wxLogin) {
      //GG
      return false
    }

    //3. wx.getUserInfo
    console.log('begin getUserInfo')
    let getUserInfo = await this.getUserInfo(reqType, wxLogin)

    if (!getUserInfo) {
      //GG
      return false
    }

    if (getUserInfo.state === 'refused') {
      //3.1 redo auth
      getUserInfo = await this.reauth(reqType, wxLogin)
    }

    if (getUserInfo && getUserInfo.state === 'success') {
      //4 dream login
      let dreamLogin = await this.dreamLogin(getUserInfo)

      console.log('dreamLogin : ',wxLogin,  dreamLogin, Config.api_base + '/login/xcx', Config)
      if (dreamLogin) {
        if (dreamLogin.data.localSession) {
          this.cache.cacheLocalSession(dreamLogin.data.localSession)
          this.cache.cacheDreamUser(dreamLogin.data.userInfo)
          return true
        } else {
          wx.showModal({
            title: '服务器错误',
            content: dreamLogin.data.message || '服务器错误',
            showCancel: false
          })
        }
      }
    }

    return false
  }

  checkSession() {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: () => {
          return resolve(!!this.cache.getLocalSession().sid)
        },
        fail: () => {
          return resolve(false)
        }
      })
    })
  }

  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          resolve(res)
        },
        fail: () => {
          wx.showModal({
            title: '授权失败',
            content: '微信授权失败，请检查网络是否正常',
            showCancel: false
          })
          resolve(false)
        }
      })
    })
  }

  getUserInfo(reqType, res) {
    return new Promise((resolve) => {
      wx.getUserInfo({
        success: (res1) => {
          this.cache.cacheWxUser(res1.userInfo)
          //注意：如果用户已经授权过且wx session未失效，
          //则此时会直接从缓存中提取用户信息而不用弹窗请求登录授权
          res1['code'] = res.code
          resolve({state: 'success', res: res1})
        },
        fail: () => {
          if (reqType === 'try_page') {
            //如果只是试着请求用户登录，则用户拒绝后不需要再次请求登录
            resolve(false)
            return
          }
          // 如果用户拒绝了授权
          resolve({state: 'refused', res: res})
        }
      })
    })
  }

  dreamLogin(userInfo) {
    return wepy.request({
      url: Config.api_base + '/login/xcx',
      method: 'POST',
      data: userInfo.res,
      header: { 'x-client-type': Config.client_type }
    })
  }

  reauth(reqType, res) {
    if (undefined == wx.openSetting) {
      this.auth_feedback(reqType)
      return
    }

    return this.reauthModal(reqType, res)
  }

  auth_feedback(reqType) {
    return new Promise((resolve, reject) => {
      if (reqType == 'page') {
        wx.showToast({
          title: '你拒绝了登录授权，即将回到首页...',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/homepage/index',
              })
              reject && reject()
            }, 1000)
          }
        })
      } else {
        wx.showModal({
          title: '请求失败',
          content: '你拒绝了登录授权，无法完成请求',
          showCancel: false
        })
        reject && reject()
      }
    })
  }

  reauthModal(reqType, res) {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: '重新授权登录',
        content: '授权登录后你将享有更多权限，请到小程序设置中打开用户信息授权',
        showCancel: true,
        cancelText: '取消',
        confirmText: '去设置',
        success: (res2) => {
          if (res2.confirm) {
            // 再次授权
            wx.openSetting({
              success: (res3) => {
                if (res3.authSetting['scope.userInfo']) {
                  wx.getUserInfo({
                    success: (res4) => {
                      this.cache.cacheWxUser(res4.userInfo)
                      res4['code'] = res.code
                      resolve && resolve({state: 'success', res: res4})
                    }
                  })
                } else {
                  this.auth_feedback(reqType)
                }
              }
            })
          } else if (res2.cancel) {
            this.auth_feedback(reqType)
          }
        }
      })
    })
  }
}

export default Auth
